<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;

class WorkpaperController extends AdminController
{
    protected string $table = 'work_papers';

    protected string $model = "workPaper";

    protected array $type = [
        1=>'日报',
        2=>'周报',
        3=>'月报'
    ];

    #[NoReturn] public function init(): void
    {
        $this->routeWhiteLst = ['workpaper@receipt','workpaper@receiptuser'];
        parent::init();
    }

    /**
     * 我的汇报列表
     * @return void
     */
    #[NoReturn] public function indexAction(): void
    {
        try {
            $sort = Request::input("sort");
            $orderBy = match ($sort)
            {
                "-id"=>'asc',
                default => 'desc',
            };
            $sql = WorkPaperModel::query()->with(['user'=>function ($query) {
                $query->selectRaw("nickname,id,avatar");
            }])->where("user_id",$this->member_id);
            if (Request::input("time")) {
                if (is_array(Request::input("time"))) {
                    $sql->whereBetween("created_at",Request::input("time"));
                }else {
                    $sql->whereDate("created_at",Request::input("time"));
                }
            }
            $sql->when(Request::input("type"),function ($query,$type){
                $query->where("type",$type);
            });
            $data = $sql->orderBy("id",$orderBy)
                ->paginate(Request::input("limit",10),['*'],NULL,Request::input("p",1));
            $_result = collect($data->items())->toArray();
            foreach ($_result as $key=>$vo) {
                if ($vo['user']) {
                    $user = array_column($vo['user'], 'nickname');
                    $_result[$key]['users'] = implode(",",$user);
                }else {
                    $_result[$key]['users'] = "";
                }
                $_result[$key]['type'] = $this->type[$vo['type']];
            }
            $result = [
                'items' => $_result,
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 修改
     * @return void
     */
    protected function update(): void
    {
        DB::beginTransaction();
        try {
            $params  = Request::all();
            $this->cleanCache();
            if (Request::input("id") !== null) {
                App::make($this->getModelMame())->where("id",Request::input("id"))->update($params);
                foreach ($params['user_id'] as $vo) {
                    $insert[] = [
                        'user_id'=>$vo,
                        'org_id'=>$this->org['id']??1,
                        'work_paper_id'=>$params['id'],
                        'created_at'=>date("Y-m-d H:i:s")
                    ];
                }
                WorkPaperUserModel::where("work_paper_id",$params['id'])->delete();
                WorkPaperUserModel::insert($insert);
                DB::commit();
                $this->apiSuccess([],"更新成功",20000);
            }else {
                $userId = $params['user_id'];
                $params['uuid'] = (string)Str::uuid();
                $params['created_at'] = date("Y-m-d H:i:s");
                if (DB::schema()->hasColumn($this->table, "org_id")) {
                    $params['org_id'] = $this->org['id'];
                }
                if (DB::schema()->hasColumn($this->table, "user_id")) {
                    $params['user_id'] = $this->member_id;
                }
                $res =  App::make($this->getModelMame())->insertGetId($params);
                foreach ($userId as $vo) {
                    $insert[] = [
                        'user_id'=>$vo,
                        'org_id'=>$this->org['id']??1,
                        'work_paper_id'=>$res,
                        'created_at'=>date("Y-m-d H:i:s")
                    ];
                }
                WorkPaperUserModel::insert($insert);
                $info =  App::make($this->getModelMame())->where('id',$res)->first();
                DB::commit();
                $this->apiSuccess( $info->toArray(),"新增成功",20000);
            }
        } catch (Exception $exception) {
            DB::rollBack();
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

	/**
     * 显示
     * @return void
     */
    #[NoReturn] protected function operate(): void
    {
        $info = WorkPaperModel::query()
		->join("users","users.id","=","work_papers.user_id")
		->join("organizations","organizations.id","=","work_papers.org_id")
		->with(['user'=>function ($query) {
                $query->selectRaw("nickname,id,avatar");
            }])
		->where('work_papers.id', Request::input("ids"))
		->selectRaw("ws_work_papers.*,ws_users.nickname,ws_users.avatar,ws_organizations.title as org_name")
		->first();
        if (!$info) $this->apiError("数据不存在");
		$info = $info->toArray();
        $is_read = WorkPaperUserModel::query()->where("work_paper_id",$info['id'])
            ->where("user_id",$this->member_id)
            ->where("is_read",1)
            ->exists();
        $info['is_read'] = $is_read ? 1 : 0;
		$info['type_name'] = $this->type[$info['type']];
		foreach($info['user'] as $vo) {
			$info['users'][] = $vo['nickname'];
		}
		$info['is_owner'] = $this->member_id==$info['user_id']?1:0;
        $readUser = WorkPaperUserModel::query()
            ->join("users","users.id","=","work_paper_users.user_id")
            ->where("work_paper_id",Request::input("id"))
            ->where("is_read",1)
            ->selectRaw("ws_users.nickname")
            ->get()->toArray();
        foreach ($readUser as $vo) {
            $info['read_users'][] = $vo['nickname'];
        }
        $this->apiSuccess($info,"获取成功",20000);
    }

    /**
     * 汇报看板
     * @return void
     */
    #[NoReturn] public function boardAction(): void {
        try {
            $sort = Request::input("sort");
            $orderBy = match ($sort) {
                "-id"=>'asc',
                default => 'desc',
            };
            $sql = WorkPaperModel::query()
                ->join("users","users.id","=","work_papers.user_id")
                ->join("organizations","organizations.id","work_papers.org_id")
                ->when(Request::input("type"),function ($query,$value){
                    $query->where("work_papers.type",$value);
                })
                ->when(Request::input("user_id"),function ($query,$value){
                    $query->whereIn("work_papers.user_id",$value);
                });
            if (Request::input("query_type")==1) {
                $sql->where("work_papers.user_id",Request::input("receipt_user_id"));
            }else {
                $sql->where($this->where)->when($this->whereIn,function ($query,$value){
                    foreach ($value as $item) {
                        $query->whereIn($item[0], $item[1]);
                    }
                });
            }
            $sql->when(Request::input("is_read"),function ($query,$value){
                if ($value==1) {
                    $query->whereHas("paperUser",function ($query){
                        $query->where("user_id",$this->member_id)->where("is_read",1);
                    });
                }else {
                    $query->whereHas("paperUser",function ($query){
                        $query->where("user_id",$this->member_id)->where("is_read",0);
                    });
                }
            });
            if (Request::input("time")) {
                if (is_array(Request::input("time"))) {
                    $sql->whereBetween("work_papers.created_at",Request::input("time"));
                }else {
                    $sql->whereDate("work_papers.created_at",Request::input("time"));
                }
            }
            $data = $sql->orderBy("id",$orderBy)
                ->selectRaw("ws_work_papers.*,ws_users.nickname,ws_organizations.title as org_name,ws_users.avatar")
                ->paginate(Request::input("limit",10),['*'],NULL,Request::input("p",1));
            $_result = collect($data->items())->toArray();
            foreach ($_result as $key=>$vo) {
                $_result[$key]['type_name'] = $this->type[$vo['type']];
            }
            $result = [
                'items' => $_result,
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 查看回执
     * @return void
     */
    #[NoReturn] public function receiptAction(): void
    {
        try {
            $info = WorkPaperUserModel::query()->where("work_paper_id",Request::input("id"))
                ->where("user_id",$this->member_id)->first();
            if (!$info) $this->apiError("数据不存在");
            if ($info['is_read']==1) $this->apiError("已回执，请不要重复操作");
            WorkPaperUserModel::where("work_paper_id",Request::input("id"))
                ->where("user_id",$this->member_id)->update([
                    'is_read'=>1,
                    'reply_content'=>Request::input("reply_content"),
                    'reply_at'=>date("Y-m-d H:i:s")
            ]);
            $this->apiSuccess([],"反馈成功",20000);
        } catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 获取看板人员列表
     * @return void
     */
    #[NoReturn] public function receiptUserAction(): void
    {
        try {
            $data = WorkPaperModel::query()
                ->join("users", "users.id", "=", "work_papers.user_id")
                ->join("organizations", "organizations.id", "work_papers.org_id")
                ->where($this->where)
                ->when($this->whereIn,function ($query,$value){
                    foreach ($value as $item) {
                        $query->whereIn($item[0], $item[1]);
                    }
                })
                ->selectRaw("ws_users.id,ws_users.nickname,ws_users.avatar,ws_organizations.title as org_name")
                ->get()->toArray();
            $this->apiSuccess($data, "获取成功", 20000);
        }catch (Exception $exception){
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
